
import { loginService } from '@gyk/gyk-api'
import { tokenUtils, cacheUtils, LocalCacheKeys } from '@gyk/gyk-utils'
import { defineStore } from 'pinia'
import STORE_NAMES from '../store-names'
import { userState } from '../types'

const useUserStore = defineStore(STORE_NAMES.USER, {
  state: (): userState => {
    return {
      token: tokenUtils.getToken(),
      name: '',
      avatar: '',
      roles: [],
      permissions: [],
      expires_in: '',
    }
  },
  getters: {

  },
  actions: {
    // 登录
    async Login(userInfo: any): Promise<void> {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise<void>((resolve, reject) => {
        loginService.login({ username, password, code, uuid }).then(res => {
          let data = res.data
          tokenUtils.setToken(data.access_token)
          this.token = data.access_token
          tokenUtils.setExpiresIn(data.expires_in)
          this.expires_in = data.expires_in
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    async GetInfo(): Promise<any> {
      return new Promise((resolve, reject) => {
        loginService.getInfo().then(res => {
          const user = res.user
          const avatar = user.avatar
          if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            this.roles = res.roles
            this.permissions = res.permissions
          } else {
            this.roles = ['ROLE_DEFAULT']
          }
          // 将permissions存储到localCache，用来做自定义权限校验的指令
          cacheUtils.localCache.setJSON(LocalCacheKeys.LOCAL_PERMISSIONS_KEY, this.permissions)
          cacheUtils.localCache.setJSON(LocalCacheKeys.LOCAL_ROLES_KEY, this.roles)
          this.name = user.userName
          this.avatar = avatar
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 刷新token
    RefreshToken(): Promise<void> {
      return new Promise<void>((resolve, reject) => {
        loginService.refreshToken().then(res => {
          this.expires_in = res.data
          tokenUtils.setExpiresIn(res.data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut(): Promise<void> {
      return new Promise<void>((resolve, reject) => {
        loginService.logout().then(() => {
          this.token = ''
          this.roles = []
          this.permissions = []
          tokenUtils.removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut(): Promise<void> {
      return new Promise<void>(resolve => {
        this.token = ''
        tokenUtils.removeToken()
        resolve()
      })
    }
  }
})

export default useUserStore